package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author ghy
 * @version 1.0.1
 * @date 2023-04-20 09:55:18
 */
@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut("@annotation(com.sky.anno.AutoFill) && execution(* com.sky.mapper.*.*(..))")
    public void pt(){}

    @Before("pt()")
    public void autoFillField(JoinPoint joinPoint) throws Exception {
        log.warn("AutoFillAspect autoFillField --------->");
        //填充逻辑
        //1.得到方法上的注解对象
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();   //获取方法的Method对象
        AutoFill autoFill = method.getAnnotation(AutoFill.class);//获取方法上的注解
        OperationType value = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if(args != null && args.length > 0) {
            Object entity = args[0];   //得到更新或增加方法的第一个参数
            Class<?> clazz = entity.getClass();
            //2.判断是更新还是增加
            //2.1 更新，补充更新时间，更新人
            Long empId = BaseContext.getCurrentId();
            LocalDateTime now = LocalDateTime.now();
            Method setUpdateTimeMethod = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);   //通过反射获取方法对象
            setUpdateTimeMethod.invoke(entity, now);   //反射调用方法
            Method setUpdateUserMethod = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);   //通过反射获取方法对象
            setUpdateUserMethod.invoke(entity, empId);

            if (value == OperationType.INSERT) {
                Method setCreateTimeMethod = clazz.getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);   //通过反射获取方法对象
                setCreateTimeMethod.invoke(entity, now);   //反射调用方法
                Method setCreateUserMethod = clazz.getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);   //通过反射获取方法对象
                setCreateUserMethod.invoke(entity, empId);
            }
            log.warn("entity {}", entity);
        }

    }

}
